package org.theSeed.web.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.function.Supplier;

import static org.theSeed.web.sysEnum.FilterOrder.REQUEST_LOG;

/**
 * 请求信息日志过滤器
 */
@Slf4j
public class ReqAndResLogFilter implements Filter, Ordered {
    public ReqAndResLogFilter() {
    }

    public ReqAndResLogFilter(Integer orderNum) {
        this.orderNum = orderNum;
    }

    public ReqAndResLogFilter(Supplier<Boolean> logFlagSupplier) {
        this.logFlagSupplier = logFlagSupplier;
    }

    public ReqAndResLogFilter(Integer orderNum, Supplier<Boolean> logFlagSupplier) {
        this.orderNum = orderNum;
        this.logFlagSupplier = logFlagSupplier;
    }

    protected Integer orderNum = REQUEST_LOG.getCode();

    /**
     * 开启请求日志记录标识
     */
    protected Supplier<Boolean> logFlagSupplier = ()->{return true;};

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Boolean logFlag = logFlagSupplier.get();
        if (logFlag){
            //请求体处理
            HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
            String pathInfo = httpServletRequest.getRequestURI();
            if (logFlag){
                if (servletRequest instanceof RepeatReadFilter.CachedBodyHttpServletRequestWrapper){
                    log.info("请求路径:{},请求参数{}",pathInfo,((RepeatReadFilter.CachedBodyHttpServletRequestWrapper)servletRequest).getBody());
                }else{
                    log.error("日志过滤器请求信息不支持");
                }
            }

            filterChain.doFilter(servletRequest,servletResponse);

            if (logFlag){
                if (servletResponse instanceof RepeatReadFilter.CachedBodyHttpServletResponseWrapper){
                    log.info("请求路径:{},响应结果{}",pathInfo,((RepeatReadFilter.CachedBodyHttpServletResponseWrapper)servletResponse).getContentAsString());
                }else{
                    log.error("日志过滤器响应信息不支持");
                }
            }
        }else
            filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
